import { defineStore } from 'pinia'
import { useRequest } from '~/composables/useRequest'

export const useCategoryStore = defineStore('categoryStore', () => {
  const { requestGet, requestPost } = useRequest()
  const state = reactive({
    curParentCategoryId: null,
    curCategoryId: null,
    goodsList: { data: [], totalElements: 0 },
  })
  const i18n = useI18n()
  const categoryTree = useMyStorage('categoryTree', [])
  const subCategories = computed(() => {
    return categoryTree.value.find((item) => item.id === state.curParentCategoryId)?.subCategories || []
  })
  return {
    ...toRefs(state),
    categoryTree,
    subCategories,
    setCategoryId({ parentCategoryId, categoryId }) {
      state.curParentCategoryId = +parentCategoryId
      state.curCategoryId = +categoryId
    },
    async initCategoryTree() {
      const { data } = await requestGet('/app/goods/categoryTree', {
        params: { isNigeria: +(i18n.locale.value === 'ng') },
        hideError: true,
      })
      categoryTree.value = data
    },
    async initGoodsByCategoryId(num = 1, size = 10) {
      const { curCategoryId, curParentCategoryId } = state
      const { data: data } = await requestGet(`/app/goods/getGoodsByCategoryId/${num}/${size}`, {
        params: { categoryId: curCategoryId || curParentCategoryId, isParentCategory: +!curCategoryId },
      })
      state.goodsList = data
    },
  }
})
